<template>
    <div class="maintenance-plan">
        <!-- 搜索区域 -->

        <div class="search-area">
            <el-card class="stat-card"
                style="width: 70%; margin: 0 auto; padding: 20px; border-radius: 8px; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);">
                <!-- 添加gutter并优化列布局 -->
                <el-row :gutter="20" class="mb-2">
                    <el-col :span="5">
                        <el-input v-model="searchForm.createTime" placeholder="创建时间" class="search-input"></el-input>
                    </el-col>
                    <el-col :span="10">
                        <el-input v-model="searchForm.remark" placeholder="维修内容" class="search-input"></el-input>
                    </el-col>
                    <!-- 使用offset将按钮推到右侧 -->
                    <el-col :span="4" :offset="5">
                        <el-button type="primary" class="add-btn" @click="openAddDialog">添加新的维修计划</el-button>
                    </el-col>
                </el-row>
                <el-row style="margin-top: 10px;">
                    <el-col :span="24" style="text-align: left;">
                        <el-button type="primary" class="search-button" @click="handleSearch">查找</el-button>
                    </el-col>
                </el-row>
            </el-card>
        </div>

        <!-- 表格区域 -->
        <el-card class="table-card" style="width: 70%; margin: 0 auto;">
            <el-table :data="paginatedData" border style="width: 100%">
                <el-table-column prop="id" label="订单ID" width="100" />
                <el-table-column prop="createTime" label="创建时间" width="200" />
                <el-table-column prop="equipmentId" label="设备ID" width="100" />
                <el-table-column prop="remark" label="维修内容" />
                <el-table-column prop="status" label="状态" width="120">
                    <template #default="scope">
                        {{ formatStatus(scope.row.status) }}
                    </template>
                </el-table-column>
                <el-table-column prop="userId" label="负责人ID" width="120" />
            </el-table>

            <!-- 分页组件 -->
            <div class="pagination-container">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[5, 10, 20]" :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>
        </el-card>

        <!-- 添加维修计划弹窗 -->
        <el-dialog v-model="addDialogVisible" title="添加维修计划" width="600px">
            <el-form :model="form" label-width="140px" class="add-form">
                <el-form-item label="设备ID" prop="equipmentId">
                    <el-input v-model.number="form.equipmentId" placeholder="请输入设备ID" style="width: 100%" required />
                </el-form-item>
                <el-form-item label="维修内容" prop="content">
                    <el-input v-model="form.content" placeholder="请输入维修计划内容" style="width: 100%" required />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleAdd">创建维修计划</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 删除选择维修人员弹窗 -->
    </div>
</template>

<script>
import { Search } from '@element-plus/icons-vue';
import { ElIcon } from 'element-plus';
import { ref, reactive, computed, onMounted } from 'vue';
import { ElTable, ElTableColumn, ElInput, ElButton, ElDialog, ElForm, ElFormItem, ElTimePicker, ElPagination, ElMessage } from 'element-plus';
import request from '@/utils/request';

export default {
    name: 'MaintenancePlan',
    components: {
        ElIcon, Search, ElTable, ElTableColumn, ElInput, ElButton, ElDialog, ElForm, ElFormItem, ElTimePicker, ElPagination
    },
    setup() {
        // 搜索表单数据
        const searchForm = reactive({
            createTime: '',
            remark: ''
        });

        // 维修计划数据
        const maintenancePlans = ref([]);
        const currentPage = ref(1);
        const pageSize = ref(10);
        const total = ref(0);
        // 添加弹窗相关变量
        const addDialogVisible = ref(false);

        // 只保留最新的表单定义
        const form = reactive({
            equipmentId: null,      // 设备ID
            content: ''             // 维修计划内容
        });

        // 状态格式化
        const formatStatus = (status) => {
            const statusMap = { 0: '未处理', 1: '处理中', 2: '已完成', 3: '已取消' };
            return statusMap[status] || '未知状态';
        };

        // 分页数据计算
        const paginatedData = computed(() => {
            const startIndex = (currentPage.value - 1) * pageSize.value;
            return maintenancePlans.value.slice(startIndex, startIndex + pageSize.value);
        });

        // 获取维修计划数据
        const fetchMaintenancePlans = async () => {
            try {
                const response = await request.get('/admin/getAllRepair');
                if (response.code === 200) {
                    maintenancePlans.value = response.data || [];
                    total.value = maintenancePlans.value.length;
                } else {
                    ElMessage.error('获取维修计划失败: ' + (response.msg || '未知错误'));
                }
            } catch (error) {
                ElMessage.error('网络请求失败，请检查连接');
                console.error('API请求错误:', error);
            }
        };

        // 页面加载时获取数据
        onMounted(() => {
            fetchMaintenancePlans();
        });

        // 分页事件处理
        const handleSizeChange = (val) => {
            pageSize.value = val;
            currentPage.value = 1;
        };

        const handleCurrentChange = (val) => {
            currentPage.value = val;
        };

        // 搜索方法
        const handleSearch = () => {
            // 这里可以添加搜索逻辑
            fetchMaintenancePlans();
        };



        // 添加维修计划处理函数
        const handleAddMaintenance = async () => {
            // 验证输入并转换为整数数组
            const maintenanceId = Number(form.maintenanceId);
            if (isNaN(maintenanceId) || maintenanceId <= 0) {
                ElMessage.warning('请输入有效的订单ID');
                return;
            }

            if (!form.maintenancePerson.trim()) {
                ElMessage.warning('请输入维修人员ID');
                return;
            }

            // 处理逗号分隔的ID字符串，转换为整数数组
            const userIds = form.maintenancePerson.split(',')
                .map(id => parseInt(id.trim()))
                .filter(id => !isNaN(id));

            if (userIds.length === 0) {
                ElMessage.warning('请输入有效的维修人员ID');
                return;
            }

            try {
                // 构造符合API要求的请求参数
                const response = await request.post('/admin/arrangementMaintenanceSchedule', {
                    maintenanceId: form.maintenanceId,
                    userIds: userIds
                });

                if (response.code === 200) {
                    ElMessage.success('维修计划添加成功');
                    addDialogVisible.value = false;
                    fetchMaintenancePlans(); // 刷新维修计划列表
                } else {
                    ElMessage.error('添加失败: ' + (response.msg || '未知错误'));
                }
            } catch (error) {
                ElMessage.error('网络请求失败，请检查连接');
                console.error('API请求错误:', error);
            }
        };

        // 打开添加弹窗 - 重置表单
        const openAddDialog = () => {
            addDialogVisible.value = true;
            // 重置表单为初始状态
            Object.assign(form, {
                equipmentId: null,
                content: ''
            });
        };

        // 添加维修计划 - 保留最新实现
        const handleAdd = async () => {
            // 验证所有必填字段
            if (!form.equipmentId || form.equipmentId <= 0) {
                ElMessage.warning('请输入有效的设备ID');
                return;
            }

            if (!form.content.trim()) {
                ElMessage.warning('请输入维修计划内容');
                return;
            }

            try {
                const response = await request.post('/users/repairRequests', {
                    equipmentId: form.equipmentId,
                    remark: form.content  // 将参数名 content 改为 remark
                });
                // 临时方案：直接显示接口返回消息并刷新列表
                ElMessage.success(response.data.msg || '维修计划创建成功');
                addDialogVisible.value = false;
                fetchMaintenancePlans();
            } catch (error) {
                // 增强错误处理，显示具体错误信息
                const errorMsg = error.response?.data?.msg || error.message || '网络请求失败，请检查连接';
                ElMessage.error(`提交失败: ${errorMsg}`);
                console.error('API请求错误:', error);
            }
        };

        return {
            searchForm,
            maintenancePlans,
            paginatedData,
            currentPage,
            pageSize,
            total,
            formatStatus,
            handleSearch,
            handleSizeChange,
            handleCurrentChange,
            openAddDialog,
            handleAdd,
            addDialogVisible,
            form
        };
    }
};
</script>

<style scoped>
.maintenance-plan {
    padding: 20px;
}

.search-area {
    margin-bottom: 20px;
}

/* 表格卡片样式 */
.table-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin-bottom: 20px;
}

/* 表格样式 */
:deep(.el-table) {
    border: none !important;
}

/* 表头样式 */
:deep(.el-table__header-wrapper .el-table__header) {
    background-color: #1890ff !important;
}

:deep(.el-table__header-wrapper th.el-table__cell) {
    background-color: #1890ff !important;
    color: white !important;
    border-bottom: 1px solid #e8e8e8 !important;
    font-weight: 500;
}

/* 表格行悬浮效果 */
::v-deep .el-table .el-table__row {
    transition: all 0.3s ease !important;
    height: auto !important;
}

::v-deep .el-table .el-table__body tr:hover>td {
    background-color: #1890ff !important;
    color: #fff !important;
    font-size: 15px !important;
    /* 删除以下差异化属性 */
    /* font-weight: 500;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
    transform: scale(1.015);
    transform-origin: center left;
    z-index: 10 !important;
    position: relative;
    border-radius: 8px !important; */
}

/* 删除单元格内边距调整代码 */
/* ::v-deep .el-table .el-table__row:hover .cell {
    padding: 14px 15px !important;
} */

/* 删除冲突的悬浮样式定义 */
/* :deep(.el-table__body-wrapper .el-table__row:hover > td) {
    background-color: #e6f7ff !important;
    transform: scale(1.01);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
} */

/* 分页样式 */
.pagination-container {
    margin-top: 16px;
    text-align: right;
    padding: 10px;
}

/* 搜索按钮样式 */
.search-button {
    background-color: #1890ff !important;
    color: white !important;
    border: none !important;
}

/* 对话框样式 */
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>
